from django.utils.deprecation import MiddlewareMixin
from django.urls import resolve
from django.utils import timezone
from main.models import BrowseHistory, Article

class BrowseHistoryMiddleware(MiddlewareMixin):
    """记录用户浏览历史的中间件"""

    def process_response(self, request, response):

        # 只有登录用户才记录浏览历史
        if not request.user.is_authenticated:
            return response

        # 获取当前请求的URL解析结果
        resolver_match = resolve(request.path)

        # 检查是否是文章详情页
        if resolver_match.url_name == 'article_detail' and request.method == 'GET':
            try:
                # 获取文章ID
                article_id = resolver_match.kwargs.get('pk')
                if article_id:
                    # 尝试获取文章
                    article = Article.objects.get(pk=article_id)
                    # 每次浏览都创建新的浏览历史记录，以准确统计浏览次数
                    BrowseHistory.objects.create(
                        user=request.user,
                        article=article,
                        browse_time=timezone.now()
                    )
            except Article.DoesNotExist:
                # 文章不存在，不记录
                pass
            except Exception as e:
                pass
                # logger.error(f"记录浏览历史时出错: {str(e)}")
        else:
            pass
            # logger.debug("不是文章详情页，不记录浏览历史")

        return response